class UsersController < ApplicationController
  load_and_authorize_resource :only => [:show,:index,:destroy,:edit,:update]
  helper_method :sort_column, :sort_direction
  
  # GET /users
  # GET /users.json
  def index
    @users = User.where(:deleted=>nil).search(params[:search]).order(sort_column + " " + sort_direction).paginate(:per_page => 10, :page => params[:page])
    respond_to do |format|
      format.html {render :layout => "new"}# index.html.erb
      format.json { render :json => @users }
    end
  end
  
  # GET /users/1
  # GET /users/1.json
  def show
    @user = User.find(params[:id])

    respond_to do |format|
      format.html # show.html.erb
      format.json { render :json => @user }
    end
  end
  
  # GET /users/new
  # GET /users/new.json
  def new
    @user = User.new

    respond_to do |format|
      format.html # new.html.erb
      format.json { render :json => @user }
    end
  end

  # GET /users/1/edit
  def edit
    @user = User.find(params[:id])
  end

  # POST /users
  # POST /users.json
  def create
    @user = User.new(params[:user])
    respond_to do |format|
      if @user.save
        gflash :success => { :value => "Creacion exitosa",:title => "Usuario creado" } 
        format.html { redirect_to @user }
        format.json { render :json => @user, :status => :created, :location => @user }
      else
        format.html { render :action => "new" }
        format.json { render :json => @user.errors, :status => :unprocessable_entity }
      end
    end
  end
  
  # PUT /users/1
  # PUT /users/1.json
  def update
    @user = User.find(params[:id])
    params[:user].delete(:role) unless current_user.priority? >= 2 
    params[:user].delete(:confirmation) unless current_user.priority? >= 2
    params[:user].delete(:locked) unless current_user.priority? >= 2 
    respond_to do |format|
      if @user.update_attributes(params[:user])
        gflash :success => { :value => "Actualizacion exitosa",:title => "Usuario actualizado" } 
        format.html { redirect_to @user }
        format.json { head :ok }
      else
        format.html { render :action => "edit" }
        format.json { render :json => @user.errors, :status => :unprocessable_entity }
      end
    end
  end

  # DELETE /users/1
  # DELETE /users/1.json
  def destroy
    @user = User.find(params[:id])
    @user.update_attributes(:deleted=>@user.id)
    
    respond_to do |format|
      format.html { redirect_to users_url }
      format.json { head :ok }
    end
  end
  
  def profile
    @user = User.find(params[:id])
     respond_to do |format|
        format.html # show.html.erb
        format.json { render :json => @user }
      end
  end
  
  def sort_column
    User.column_names.include?(params[:sort]) ? params[:sort] : "name"
  end
  
  def sort_direction
    %w[asc desc].include?(params[:direction]) ? params[:direction] : "asc"
  end

end
